package databases

import (
	"fmt"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/plugin/prometheus"
)

// 常量定义
const (
	PostgreSQLDefaultCharset = "UTF8"
	PostgreSQLDefaultPort    = 5432
	PostgreSQLTimeZone       = "Asia/Shanghai"
	PostgreSQLSSLMode        = "disable"
)

// PostgreSQLConfig PostgreSQL 数据库配置
type PostgreSQLConfig Database

// 确保实现了InitDBter接口
var _ InitDBter = (*PostgreSQLConfig)(nil)

// InitDB 初始化PostgreSQL数据库连接
func (d *PostgreSQLConfig) InitDB() *gorm.DB {
	// 设置默认值
	d.setPostgreSQLDefaults()

	// 构建DSN连接字符串
	dsn := d.buildDSN()

	// 创建数据库连接
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		panic(fmt.Sprintf("PostgreSQL数据库连接失败: %v", err))
	}

	// 配置监控指标
	if d.Metrics {
		d.setupPrometheus(db)
	}

	return db
}

// setPostgreSQLDefaults 设置PostgreSQL默认配置
func (d *PostgreSQLConfig) setPostgreSQLDefaults() {
	if d.Charset == "" {
		d.Charset = PostgreSQLDefaultCharset
	}
	if d.Port == 0 {
		d.Port = PostgreSQLDefaultPort
	}
}

// buildDSN 构建PostgreSQL DSN连接字符串
func (d *PostgreSQLConfig) buildDSN() string {
	return fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=%s TimeZone=%s client_encoding=%s",
		d.Host, d.Username, d.Password, d.Database, d.Port, PostgreSQLSSLMode, PostgreSQLTimeZone, d.Charset)
}

// setupPrometheus 配置Prometheus监控
func (d *PostgreSQLConfig) setupPrometheus(db *gorm.DB) {
	err := db.Use(prometheus.New(prometheus.Config{
		DBName:          d.Name,
		RefreshInterval: PrometheusRefresh,
		StartServer:     true,
		HTTPServerPort:  PrometheusHTTPPort,
		MetricsCollector: []prometheus.MetricsCollector{
			&prometheus.Postgres{
				VariableNames: []string{"Threads_running"},
			},
		},
	}))
	if err != nil {
		panic(fmt.Sprintf("配置Prometheus监控失败: %v", err))
	}
}

func (d *PostgreSQLConfig) TRUNCATETable(db *gorm.DB, tableName string) error {
	return db.Exec(fmt.Sprintf("TRUNCATE TABLE %s RESTART IDENTITY", tableName)).Error
}
